<template>
    <el-menu :collapse="!settingStore.isFold" class="menu-container" unique-opened text-color="#fff"
        active-text-color="#1E90FF" background-color="#545c64" router :default-active="settingStore.menuActive.name"
        @select="handleSelect">
        <el-menu-item index='/index'>
            <SvgIcon class="menu-title" name="首页" color="#f50"></SvgIcon>
            <span>首页</span>
        </el-menu-item>
        <MenuItem v-if="homeStore.menuTree.length > 0" :data="homeStore.menuTree">
        </MenuItem>
    </el-menu>
</template>

<script setup>
import MenuItem from './MenuItem.vue';
import SvgIcon from '../svgIcon/SvgIcon.vue';
import { useLayoutStore } from '@/stores/settings'
import { useHomeStore } from '@/stores/index'
import { ref } from 'vue';
const settingStore = useLayoutStore()
const homeStore = useHomeStore()
const handleSelect = (index, indexPath, item) => {
    if (index == "/index") {
        settingStore.menuActive.name = "/index"
        settingStore.menuActive.label = "首页"
        return
    }

    const menu = findMenu(homeStore.menuTree, index)
    settingStore.menuActive.name = index
    settingStore.menuActive.label = menu.menuName
    if (!menu) return
    if (settingStore.tabs.length <= 0 || !settingStore.tabs.some(item => item.name == menu.path)) {
        settingStore.tabs.push({
            name: menu.path,
            label: menu.menuName,
        })

    }
    console.log(settingStore.tabs)
}

/**
 * 递归查找匹配的路由
 * @param menuTree  菜单树
 * @param path 路由路径
 */
let findMenu = (menuTree, path) => {
    let i = 0
    for (; i < menuTree.length; i++) {
        if (menuTree[i].path === path && !menuTree[i].children) {
            return menuTree[i]
        } else if (menuTree[i].children != null && menuTree[i].children.length > 0) {
            const found = findMenu(menuTree[i].children, path)
            if (found) return found
        }
    }
    return null
}

</script>

<style scoped>
.menu-container {
    background-color: inherit;
}

.el-menu-item:hover {
    background-color: #263445;
}

.menu-title {
    padding-right: 10px;
}
</style>
